package cn.hxz.interceptor;

import cn.hxz.pojo.User;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Description: TODO
 * @Author: huangxinzhang
 * @Date: 2024/9/11
 **/
public class TestInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandler:" + handler);
        //获取请求的url
        String url = request.getRequestURI();
        //除了登录请求外，其他的url都进行拦截控制
        if (url.indexOf("/login")>= 0) {
            return true;
        }
        //允许公开访问
        if (url.indexOf("/toLogin")>= 0) {
            return true;
        }

        //获取session
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user_session");
        //如果user不为空，表示已登录
        if (user != null) {
            System.out.println("已登陆");
            return true;
        }
        //不符合条件，给出提是信息，并转发到登录页面
        request.setAttribute("msg", "请先登录");

        request.getRequestDispatcher("toLogin").forward(request, response);
        System.out.println("forward......");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }
}
